package com.yzkj.siot.facade.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yzkj.siot.context.CurUserCtx;
import com.yzkj.siot.domain.AdminTenant;
import com.yzkj.siot.domain.TenantUser;
import com.yzkj.siot.exp.BizExp;
import com.yzkj.siot.facade.UserFacade;
import com.yzkj.siot.result.PageParams;
import com.yzkj.siot.result.PageResponse;
import com.yzkj.siot.service.AdminTenantService;
import com.yzkj.siot.service.TenantUserService;
import com.yzkj.siot.util.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserFacadeImpl implements UserFacade {

    @Autowired
    TenantUserService tenantUserService;

    @Autowired
    AdminTenantService adminTenantService;

    @Autowired
    PageHelper<TenantUser> userPageHelper;

    @Override
    public PageResponse<TenantUser> page(PageParams<TenantUser> pageParams) {
        TenantUser where = pageParams.getEntity();

        QueryWrapper<TenantUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(TenantUser::getTenantId, CurUserCtx.get().getTenantId());

        if (where != null) {
            userQueryWrapper.lambda()
                    .like(!StringUtils.isEmpty(where.getUserName()), TenantUser::getUserName, where.getUserName())
            ;
        }

        pageParams.getOrderBy().forEach(item -> userQueryWrapper.orderBy(true, item.getIsAsc(), item.getField()));

        return userPageHelper.queryPageOrList(tenantUserService.getBaseMapper(), pageParams, userQueryWrapper);
    }

    @Override
    public TenantUser queryOne(int id) {

        TenantUser tenantUser = tenantUserService.getById(id);

        if (tenantUser == null) {
            return null;
        }

        AdminTenant tenant = adminTenantService.getById(tenantUser.getTenantId());
        tenantUser.setTenant(tenant);
        return tenantUser;
    }

    @Override
    public TenantUser saveOrUpdate(TenantUser entity) {

        // 校验用户名重复
        QueryWrapper<TenantUser> userNameQueryWrapper = new QueryWrapper<>();
        userNameQueryWrapper.lambda()
                .eq(TenantUser::getUserName, entity.getUserName())
                .eq(TenantUser::getTenantId, CurUserCtx.get().getTenantId())
                .ne(entity.getId() != null && entity.getId() != 0, TenantUser::getId, entity.getId());

        if (tenantUserService.count(userNameQueryWrapper) != 0) {
            throw new BizExp("用户名已存在");
        }

        tenantUserService.saveOrUpdate(entity);

        return queryOne(entity.getId());
    }

    @Override
    public TenantUser remove(int id) {
        return null;
    }

    @Override
    public Boolean batchRemove(List<Integer> idList) {
        return null;
    }

    @Override
    public Boolean batchSave(List<TenantUser> entities) {
        return null;
    }
}
